// socket功能
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import store from '@/store/'
import { getMessageInfoList } from '@/api/login'

export function connectionSocket () {
  const socket = new SockJS(process.env.VUE_APP_API_BASE_URL + 'websocket')
  // 连接SockJS的endpoint名称为"bullet"
  console.log('socket连接地址：' + process.env.VUE_APP_API_BASE_URL + 'websocket')
  // 获取STOMP子协议的客户端对象
  const stompClient = Stomp.over(socket)
  // 定义客户端的认证信息,按需求配置
  // const headers = {
  //   Authorization: store.getters.token
  // }

  // 拦截输出的一大堆垃圾信息
  stompClient.debug = function (str) {
  }
  // 向服务器发起websocket连接
  const user = {
    userid: store.getters.userInfo.companyId,
    username: store.getters.userInfo.companyName
  }
  stompClient.connect(user, () => {
    stompClient.subscribe('/userSys/' + store.getters.userInfo.companyId, (response) => { // 订阅服务端提供的某个topic
      if (response.body) {
        const repObj = JSON.parse(response.body)
        if (repObj.websocketType === 'MSG') {
          // 智感安防首页，人脸预警数据推送
          // if (repObj.messageTitle) {
            getMessageInfoList().then(res => {
              store.commit('SET_SYS_MESSAGE_COUNT', res.result.dataCount)
              store.commit('SET_SYS_MESSAGE_LIST', res.result.dataMessageList)
            })
          // }
        }
      }
    })
    // eslint-disable-next-line handle-callback-err
  }, (err) => {
    // 连接发生错误时的处理函数
    console.log('失败')
  })
}
